package com.hd.trans.ui.activity.customize

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.bumptech.glide.Glide
import com.hd.trans.R
import com.hd.trans.TranslationInterior
import com.hd.trans.TranslationUI
import com.hd.trans.camerax.CameraFragment
import com.hd.trans.camerax.CameraLightMode
import com.hd.trans.camerax.CaptureCallback
import com.hd.trans.camerax.LuminosityListener
import com.hd.trans.common.Constants
import com.hd.trans.databinding.ActivityPictureTranslateBinding
import com.hd.trans.db.DataBaseMgr
import com.hd.trans.db.bean.FileTranslateRecord
import com.hd.trans.db.bean.HuDunLanguage
import com.hd.trans.db.bean.MediaItem
import com.hd.trans.dialog.RCCameraLightPop
import com.hd.trans.extension.existsFile
import com.hd.trans.extension.observe
import com.hd.trans.files.aty.MediaAlbumActivity
import com.hd.trans.files.bean.MediaOptions
import com.hd.trans.files.bean.MimeType
import com.hd.trans.framework.dialog.LanguageDialog
import com.hd.trans.framework.dialog.LanguageDialogType
import com.hd.trans.homefun.EventCode
import com.hd.trans.homefun.RecordType
import com.hd.trans.limit4Use.LimitUseListener
import com.hd.trans.network.PreferenceMgr
import com.hd.trans.share.AudioTimeFormatUtil
import com.hd.trans.ui.activity.CameraHomeActivity.Companion.productId
import com.hd.trans.ui.activity.CameraHomeActivity.Companion.userId
import com.hd.trans.ui.activity.PictureTransResultActivity
import com.hd.trans.ui.base.AppContextProvider
import com.hd.trans.ui.base.LimitBaseActivity
import com.hd.trans.ui.listener.ScreenOrientationListener
import com.hd.trans.ui.model.PictureTransModel
import com.hd.trans.utils.AlbumHelper
import com.hd.trans.utils.BitmapUtilsKotlin
import com.hd.trans.utils.FileUtil
import com.hd.trans.utils.FileUtilsKotlin
import com.hd.trans.utils.FileUtilsKotlin.assetRes2File
import com.hd.trans.utils.ImageUtils
import com.hd.trans.utils.LogUtil
import com.hd.trans.utils.PhotoBitmapUtils
import com.hd.trans.utils.PhotoFileUtil
import com.hd.trans.utils.ScreenUtil
import com.hd.trans.utils.ToastUtils
import com.hd.trans.utils.TrackerForTrans
import com.hd.trans.utils.VirtualToast
import com.hd.trans.utils.preference.Preferences
import id.zelory.compressor.Compressor
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import io.reactivex.ObservableOnSubscribe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import me.pqpo.smartcropperlib.SmartCropper
import java.io.File
import java.io.IOException
import java.io.InputStream

class PictureTranslateActivity: LimitBaseActivity() {

    companion object {

        @JvmStatic
        fun open(context: Context, listener: LimitUseListener? = null) {
            limitListener = listener
            val intent = Intent(context, PictureTranslateActivity::class.java)
            context.startActivity(intent)
        }
    }

    private lateinit var mDataBinding: ActivityPictureTranslateBinding
    lateinit var mDataModel: PictureTransModel
    private var flashLightMode = CameraLightMode.CLOSE
    private var mStartCameraTimeMillis = 0L
    private var twoWay: Boolean = false
    private var mFlashLightPop: RCCameraLightPop? = null
    private var cameraOrientation: Int = 0
    private var mIsDark = false
    private var virtualToast: VirtualToast? = null

    private var ta1: TranslateAnimation? = null
    private var ta2: TranslateAnimation? = null

    private val mCameraFragment by lazy {
        CameraFragment()
    }

    private val mCaptureCallback: CaptureCallback = object : CaptureCallback {
        override fun onCaptureError(e: Exception) {
//            mHandler.post {
//                stopTakePhoto()
//            }

        }

        override fun onCaptureSuccess(photoPath: String, photoUri: Uri) {
            GlobalScope.launch {
                val originalPhone =  BitmapUtilsKotlin.getBitmapFromPath(photoPath)

                var newPhone = BitmapUtilsKotlin.rotateBitmap(originalPhone, cameraOrientation)

                if (Preferences.cameraBorderDetect) {
                    val cameraCropPoints = mCameraFragment.getCropPoints()
                    if (!cameraCropPoints.isNullOrEmpty()){
                        val p = cameraCropPoints[0]
                        if (p.x > 10 && p.y > 10){
                            val smartCropPoints = SmartCropper.scan(newPhone)
                            val crop = SmartCropper.crop(newPhone, smartCropPoints)
                            newPhone.recycle()
                            newPhone = crop
                        }
                    }
                }

                File(photoPath).delete()

                processBitmap(newPhone, false)

            }

        }
    }

    private val mLuminosityListener = LuminosityListener {
        if (System.currentTimeMillis() - mStartCameraTimeMillis < 1000){
            //开启相机后的第一秒不做亮度判断，因为可能是黑屏
            return@LuminosityListener
        }
        if (flashLightMode == CameraLightMode.ALWAYS){
            return@LuminosityListener
        }

        LogUtil.d("亮度：$it")
        val isDark = it < (255 * 0.2)
        if (mIsDark != isDark){
            mIsDark = isDark
            if (isDark){
                if (virtualToast == null){
                    virtualToast = VirtualToast(mDataBinding.llLuminosityToast,mDataBinding.tvLuminosityToast)
                }
                mDataBinding.llLuminosityToast.rotation = cameraOrientation.toFloat()
                virtualToast?.showLengthLong("当前环境较暗，建议打开手电筒")
            }
        }
    }

    private val activityLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult(),
        ActivityResultCallback<ActivityResult> { result ->
            when (result.resultCode) {
                RESULT_OK -> if (result.data != null) {
                    val intent = result.data!!
                    intent.getLongExtra(Constants.HISTORY_RECORD_ID, -1L)

                    val list: ArrayList<MediaItem>? = intent.getParcelableArrayListExtra(MediaAlbumActivity.TAG_RESULT)
                    list?.let {
                        if(it.size > 0){
                            val filePath = list[0].path
                            if (!TextUtils.isEmpty(filePath)) {
                                var bm = BitmapFactory.decodeFile(filePath)
                                val degree: Int = ImageUtils.getExifOrientation(filePath)
                                if (degree != 0) { // 旋转照片角度
                                    bm = ImageUtils.rotateBitmapByDegree(bm, degree)
                                }
                                processBitmap(bm, false)
                            }
                        }
                    }

                }
            }
        })

    override val pageType: EventCode
        get() = EventCode.CAMERA_TRANS

    override fun getLayoutId(): Int {
        return R.layout.activity_picture_translate
    }

    override fun onResume() {
        super.onResume()
        startCamera()
        loadLastPhoto()
    }

    override fun onPause() {
        super.onPause()
        stopCamera()
    }

    override fun initViewsAndEvents(savedInstanceState: Bundle?) {
        super.initViewsAndEvents(savedInstanceState)
        mDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_picture_translate)
        mDataModel = ViewModelProvider(this).get(PictureTransModel::class.java)

        observe()
        initView()
        initData()
    }

    private fun observe(){
        observe(mDataModel.languageFrom) {
            mDataBinding.tvFrom.text = it.name
        }

        observe(mDataModel.languageTo) {
            dualIdentityLang(it)
            mDataBinding.tvTo.text = it.name
        }
    }

    private fun initView() {
        mCameraFragment.setCaptureCallback(mCaptureCallback)

        mDataBinding.apply {
            click = this@PictureTranslateActivity
            val langBgLayoutParams = rlLang.layoutParams
            langBgLayoutParams.width = ScreenUtil.getScreenWidth() - (resources.getDimensionPixelSize(R.dimen.dp_55dp) * 2) + (resources.getDimensionPixelSize(R.dimen.dp_10dp) * 2)
            rlLang.layoutParams = langBgLayoutParams

            llExample.isVisible = !isVip()
        }

        ScreenOrientationListener(this) { orientation->

            if(orientation != 0 && orientation != 270){
                return@ScreenOrientationListener
            }
            cameraOrientation = orientation

            //结束动画ta1、ta2
            ta1?.cancel()
            ta2?.cancel()

            if(orientation == 270){
                val screenWidth = ScreenUtil.getScreenWidth()
                val screenHeight = ScreenUtil.getScreenHeight()
                mDataBinding.tvTips.let {
                    if (it.isVisible){
                        it.animate().translationX(150f/1080f*screenWidth).translationY(650f/2110f*screenHeight).duration = 300
                    }
                }
                mDataBinding.rlLang.animate().translationX(300f/1080f*screenWidth).translationY(920f/2110f*screenHeight).duration = 300
                if (mFlashLightPop?.isShowing == true){
                    showFlashLightPop(true)
                }
            }else{
                mDataBinding.tvTips.let {
                    if (it.isVisible){
                        it.animate().translationX(0f).translationY(0f).duration = 300
                    }
                }
                mDataBinding.rlLang.animate().translationX(0f).translationY(0f).duration = 300
                if (mFlashLightPop?.isShowing == true){
                    showFlashLightPop(false)
                }
            }
            //提示文案控件旋转
            //mDataBinding.flPictureAlbum.rotation = -1.0f * it.toFloat()
            //添加旋转动画
            val rotationOrientation = (360 - orientation.toFloat())%360
            mDataBinding.flPictureAlbum.animate().rotation(rotationOrientation).duration = 300
            mDataBinding.flTakePicture.animate().rotation(rotationOrientation).duration = 300
            mDataBinding.flPictureHistory.animate().rotation(rotationOrientation).duration = 300
            mDataBinding.btnFlashlight.animate().rotation(rotationOrientation).duration = 300
            mDataBinding.btnGridLine.animate().rotation(rotationOrientation).duration = 300
            mDataBinding.btnRecognizeBorders.animate().rotation(rotationOrientation).duration = 300
            mDataBinding.btnFlashAlways.animate().rotation(rotationOrientation).duration = 300

            if (mDataBinding.llLuminosityToast.isVisible){
                mDataBinding.llLuminosityToast.animate().rotation(rotationOrientation).duration = 300
            }

            mDataBinding.tvTips.let {
                if (it.isVisible){
                    it.animate().rotation(rotationOrientation).duration = 300
                }
            }
            mDataBinding.rlLang.animate().rotation(rotationOrientation).duration = 300



        }
    }

    private fun initData() {
        val fromLangName = PreferenceMgr.getInstance().translatePreference.fileFromLanguage
        val toLangName = PreferenceMgr.getInstance().translatePreference.fileToLanguage
        mDataModel.languageFrom.value = DataBaseMgr.getInstance().getLanguageByName(fromLangName)
        mDataModel.languageTo.value = DataBaseMgr.getInstance().getLanguageByName(toLangName)

        setBorderDetect(Preferences.cameraBorderDetect)
        updateLastPhoto()
    }

    private fun loadLastPhoto(){
        AlbumHelper.getLatestPhoto(this){
            if (Preferences.latestPhotoPath != it) {
                Preferences.latestPhotoPath = it
                updateLastPhoto()
            }
        }
    }

    private fun updateLastPhoto(){
        mDataBinding.btnAlbumUpload.post {
            if (Preferences.latestPhotoPath.existsFile()){
                mDataBinding.ivLastPhoto.setImageDrawable(ColorDrawable(Color.WHITE))
                mDataBinding.btnLastPhoto.isVisible = true
                Glide.with(mDataBinding.ivLastPhoto)
                    .load(Preferences.latestPhotoPath)
                    .thumbnail(0.6f)
                    .into(mDataBinding.ivLastPhoto)
            }
            else{
                mDataBinding.btnLastPhoto.isVisible = false
            }
        }
    }

    @SuppressLint("CommitTransaction")
    private fun startCamera(){
        supportFragmentManager.beginTransaction().replace(R.id.camera_container, mCameraFragment).commitAllowingStateLoss()
        mStartCameraTimeMillis = System.currentTimeMillis()
        val mode = flashLightMode
        mCameraFragment.updateLightMode(mode)
        mCameraFragment.setLuminosityListener(mLuminosityListener)
        updateIconLight(mode)
    }

    @SuppressLint("CommitTransaction")
    private fun stopCamera(){
        supportFragmentManager.beginTransaction().remove(mCameraFragment).commitAllowingStateLoss()
        mCameraFragment.setLuminosityListener(null)
    }

    private fun dualIdentityLang(toLang: HuDunLanguage){
        twoWay = if(!TextUtils.isEmpty(toLang.fileRecognitionCode)){
            mDataBinding.ivSwitch.setImageResource(R.drawable.trans_icon_lang_reverse)
            true
        }else{
            mDataBinding.ivSwitch.setImageResource(R.drawable.trans_icon_lang_unidirectional)
            false
        }
    }

    /**选择语言弹框*/
    private fun showSelectLanguageDialog(isFrom: Boolean) {
        val dialog = LanguageDialog(
            mDataModel.languageFrom.value!!,
            mDataModel.languageTo.value!!,
            isFrom, LanguageDialogType.FILE, LanguageDialogType.TO_TEXT)
        dialog.show(supportFragmentManager, "LanguageDialog")
        dialog.setOnLanguageChangedListener(object : LanguageDialog.OnLanguageChangedListener{
            override fun onLanguageChanged(
                fromLanguage: HuDunLanguage,
                toLanguage: HuDunLanguage,
                selectedLanguage: HuDunLanguage,
            ) {
                mDataModel.setLanguageFrom(fromLanguage)
                PreferenceMgr.getInstance().translatePreference
                    .saveFileFromLanguage(fromLanguage.name)
                mDataModel.setLanguageTo(toLanguage)
                PreferenceMgr.getInstance().translatePreference
                    .saveFileToLanguage(toLanguage.name)
            }

        })
    }

    /**
     * 互换语种动画
     */
    private fun showTranslateAnimation() {
        if(!twoWay){
            ToastUtils.showNormal("${mDataModel.languageTo.value?.name}暂不支持双向翻译")
            return
        }
        if ("自动检测" == mDataModel.languageFrom.value?.name) {
            return
        }
        ta1 = TranslateAnimation(0f, (mDataBinding.lyFrom.width + mDataBinding.ivSwitch.width).toFloat(), 0f, 0f).apply {
            duration = 600
            fillAfter = true
        }
        mDataBinding.lyFrom.startAnimation(ta1)
        mDataBinding.lyFrom.bringToFront()
        ta2 = TranslateAnimation(0f, (-mDataBinding.lyTo.width - mDataBinding.ivSwitch.width).toFloat(), 0f, 0f).apply {
            duration = 600
            fillAfter = true
        }
        mDataBinding.lyTo.startAnimation(ta2)
        mDataBinding.lyTo.bringToFront()
        ta1?.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation) {}
            override fun onAnimationEnd(animation: Animation) {
                val fromTemp: HuDunLanguage? = mDataModel.languageFrom.value
                mDataModel.setLanguageFrom(mDataModel.languageTo.value)
                mDataModel.setLanguageTo(fromTemp)
                PreferenceMgr.getInstance().translatePreference.saveFileFromLanguage(mDataModel.languageFrom.value?.name)
                PreferenceMgr.getInstance().translatePreference.saveFileToLanguage(mDataModel.languageTo.value?.name)
                animation.cancel()
            }

            override fun onAnimationRepeat(animation: Animation) {}
        })
        ta2?.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation) {}
            override fun onAnimationEnd(animation: Animation) {
                animation.cancel()
            }

            override fun onAnimationRepeat(animation: Animation) {}
        })
    }

    private fun showFlashLightPop(isLandScape:Boolean){
        if (mFlashLightPop == null){
            mFlashLightPop = RCCameraLightPop(this,true,false){ mode->
                mCameraFragment.updateLightMode(mode)
                flashLightMode = mode
                updateIconLight(mode)
            }
        }
        if(mFlashLightPop?.isShowing == false){

            mFlashLightPop?.showTop(mDataBinding.btnFlashlight,flashLightMode,isLandScape)
        }
    }

    private fun updateIconLight(mode: CameraLightMode) {
        val icon = when(mode){
            CameraLightMode.OPEN -> R.mipmap.trans_flash_open
            CameraLightMode.CLOSE -> R.mipmap.trans_flash_close
            CameraLightMode.ALWAYS -> R.mipmap.trans_flash_open
            else -> R.mipmap.trans_flash_auto
        }

        mDataBinding.ivFlashlight.setImageResource(icon)
        mDataBinding.btnFlashAlways.setImageResource(if (mode == CameraLightMode.ALWAYS) R.drawable.trans_flash_always_open else R.drawable.trans_flash_always_close)
    }

    private fun toggleGridLine(){
        val level: Int = mDataBinding.btnGridLine.drawable.level
        if (level == 2){
            mDataBinding.btnGridLine.setImageLevel(1)
            mDataBinding.imgScan.isVisible = true
        }
        else{
            mDataBinding.btnGridLine.setImageLevel(2)
            mDataBinding.imgScan.isVisible = false
            mDataBinding.tvTips.isVisible = false
        }
    }

    private fun getExampleBitmap(): Bitmap? {
        var bitmap: Bitmap? = null
        try {
            val `is`: InputStream = activity.assets.open("example/file_origin_example.png")
            bitmap = BitmapFactory.decodeStream(`is`)
            `is`.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return bitmap
    }

    private fun doCamera(){
        if (!intercept(true, "拍照")) {
            requestCameraPermission {
                //埋点
                TranslationInterior.getTrackerListener().click(TrackerForTrans.PZFY, TrackerForTrans.TakePhoto)

                mCameraFragment.takePhoto(FileUtilsKotlin.getMediaOutput())
            }
        }
    }

    /**
     * 从相册中选择图片
     */
    private fun choosePhoto() {
        val options: MediaOptions = MediaOptions.build(100)
            .setMax(1)
            .setMin(1)
            .setMediaType(MediaOptions.TYPE_IMAGE)
            .setIncludeMimeType(MimeType.JPEG, MimeType.PNG, MimeType.HEIC)
        val intent = Intent(this, MediaAlbumActivity::class.java)
        intent.putExtra(MediaAlbumActivity.TAG_MEDIA_OPTIONS, options)
        activityLauncher.launch(intent)
    }

    private fun setBorderDetect(enable: Boolean){
        Preferences.cameraBorderDetect = enable
        mDataBinding.btnRecognizeBorders.post {
            mDataBinding.btnRecognizeBorders.setImageResource(if (enable) R.drawable.trans_recognize_borders_true else R.drawable.trans_recognize_borders_false)
            mCameraFragment.enableBorderDetect = enable
        }
    }

    /**
     * 图片压缩处理
     */
    private fun processBitmap(mBitmap: Bitmap?, isExperienced: Boolean) {
        if(isExperienced){
            var fileTranslateRecord = DataBaseMgr.getInstance().getFileTranslateRecordByTime(PreferenceMgr.getInstance().exampleCreateTime)
            if(fileTranslateRecord == null){
                fileTranslateRecord = FileTranslateRecord()
                fileTranslateRecord.apply {
                    createTime = System.currentTimeMillis()
                    recordType = RecordType.IMAGE
                    PreferenceMgr.getInstance().saveExampleCreateTime(createTime)
                    updateTime = createTime
                    fileName = "拍照翻译_${AudioTimeFormatUtil.formatCreateTime1(createTime)}"
                    textLanguageFrom = DataBaseMgr.getInstance().getLanguageByName("英语")
                    textLanguageTo = DataBaseMgr.getInstance().getLanguageByName("中文（简体）")
                    fileLanguageFrom = DataBaseMgr.getInstance().getLanguageByName("英语")
                    fileLanguageTo = DataBaseMgr.getInstance().getLanguageByName("中文（简体）")

                    val filePaths = arrayListOf(
                        "file_origin_example.png",
                        "file_trans_example.png",
                        "file_origin_example.untrans",
                        "file_trans_example.trans",
                        "file_inpainted_example.jpg",
                        "file_trans_example.meta"
                    )

                    filePaths.forEach {
                        if(!File(PhotoFileUtil.getPhotoDownloadPath()+it).exists()){
                            assetRes2File(
                                assets,
                                "example/$it",
                                PhotoFileUtil.getPhotoDownloadPath()+it
                            )
                        }
                    }
                    originalFilePath = PhotoFileUtil.getPhotoDownloadPath()+filePaths[0]
                    translateFilePath = PhotoFileUtil.getPhotoDownloadPath()+filePaths[1]
                    originalText = PhotoFileUtil.getPhotoDownloadPath()+filePaths[2]
                    translateText = PhotoFileUtil.getPhotoDownloadPath()+filePaths[3]
                    inpaintedFilePath = PhotoFileUtil.getPhotoDownloadPath()+filePaths[4]
                    metaFilePath = PhotoFileUtil.getPhotoDownloadPath()+filePaths[5]
                }
                DataBaseMgr.getInstance().addFileTranslateRecord(fileTranslateRecord)
            }

            //执行图片翻译
            PictureTransResultActivity.open(
                this@PictureTranslateActivity,
                null,
                fileTranslateRecord.createTime,
                productId,
                userId,
                limitListener
            )
            finish()
            return
        }

        if (mBitmap == null || mBitmap.width < 30) {
            runOnUiThread { ToastUtils.showNormal("图片尺寸太小或已损坏") }
//            mDataBinding.cameraPreview.startPreview()
            return
        }

        var pathPhoto = ""
        Observable.create(ObservableOnSubscribe { emit: ObservableEmitter<String?> ->
            val maxValue = mBitmap.width.coerceAtLeast(mBitmap.height)
            val file: File
            if (mBitmap.byteCount > 1024 * 1024 || maxValue > 1920) {
                //拍照原图
                val path: String = PhotoBitmapUtils.saveSourcePhotoToSD(mBitmap)
                pathPhoto = path
                try {
                    file = Compressor(AppContextProvider.getContext())
                        /*.setMaxWidth(1080)
                        .setMaxHeight(1920)
                        .setQuality(75)*/
                        .setCompressFormat(Bitmap.CompressFormat.JPEG)
                        .setDestinationDirectoryPath(PhotoFileUtil.getPhotoTargetPath())//压缩后图片路径
                        .compressToFile(File(path))
                    emit.onNext(file.absolutePath)
                    emit.onComplete()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            } else {
                val path: String = PhotoBitmapUtils.savePhotoToSD(mBitmap)
                emit.onNext(path)
                emit.onComplete()
            }
        }).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .compose(bindToLifecycle())
            .subscribe(object : DisposableObserver<String?>() {
                override fun onNext(filePath: String) {
                    Log.i("TransCameraHomeActivity","filePath=$filePath")
                    if (isExperienced || !intercept(true, TrackerForTrans.PZFY)) {
                        //执行图片翻译
                        PictureTransResultActivity.open(
                            this@PictureTranslateActivity,
                            filePath,
                            0,
                            productId,
                            userId,
                            limitListener
                        )
                        finish()
                    }
                }

                override fun onError(e: Throwable) {
                    Log.i("TransCameraHomeActivity","onError:${e}")
//                    mDataBinding.cameraPreview.startPreview()
                    if(!TextUtils.isEmpty(pathPhoto)){
                        //删除原图片
                        FileUtil.deleteFile(pathPhoto)
                    }
                }

                override fun onComplete() {
                    Log.i("TransCameraHomeActivity","onComplete()")
                    if(!TextUtils.isEmpty(pathPhoto)){
                        //删除原图片
                        FileUtil.deleteFile(pathPhoto)
                    }
                }
            })
    }

    override fun onViewClick(v: View?) {
        mDataBinding.apply {
            when (v) {
                ivBack -> {
                    finish()
                }
                lyFrom-> {
                    showSelectLanguageDialog(true)
                }
                lyTo-> {
                    showSelectLanguageDialog(false)
                }
                ivSwitch-> {
                    showTranslateAnimation()
                }
                btnFlashlight-> {
                    TranslationInterior.getTrackerListener().click(TrackerForTrans.PZFY, "闪光灯")
                    if(mFlashLightPop?.isShowing == true){
                        mFlashLightPop?.dismiss()
                    }else{
                        showFlashLightPop(btnFlashlight.rotation > 0)
                    }
                }
                btnFlashAlways->{
                    TranslationInterior.getTrackerListener().click(TrackerForTrans.PZFY, "手电筒")
                    val mode = if (flashLightMode == CameraLightMode.ALWAYS){
                        CameraLightMode.CLOSE
                    }
                    else{
                        CameraLightMode.ALWAYS
                    }
                    mCameraFragment.updateLightMode(mode)
                    flashLightMode = mode
                    updateIconLight(mode)
                }
                btnGridLine-> {
                    TranslationInterior.getTrackerListener().click(TrackerForTrans.PZFY, "网格线")
                    toggleGridLine()
                }
                btnAlbumUpload,btnLastPhoto-> {
                    requestStoragePermission {
                        //埋点
                        TranslationInterior.getTrackerListener().click(TrackerForTrans.PZFY, TrackerForTrans.AlbumUpload)
                        choosePhoto()
                    }
                }
                btnRecognizeBorders->{
                    TranslationInterior.getTrackerListener().click(TrackerForTrans.PZFY, "自动切边")
                    val enable = !Preferences.cameraBorderDetect
                    setBorderDetect(enable)
                    ToastUtils.showNormal("${if (enable) "已开启" else "已关闭"}自动切边")
                }
                btnTakePicture->{
                    doCamera()
                }
                //记录
                btnHistory->{
                    //埋点
                    TranslationInterior.getTrackerListener().click(TrackerForTrans.PZFY, TrackerForTrans.History)
                    TranslationUI.openCameraTransHistoryActivity(this@PictureTranslateActivity, limitListener)
                }
                //例子
                btnCloseExample -> {
                    mDataBinding.llExample.isVisible = false
                }
                //体验
                btnToExample,cdImgExample -> {
                    TranslationInterior.getTrackerListener().click(TrackerForTrans.PZFY, "示例文稿-免费体验")
                    PreferenceMgr.getInstance().translatePreference.saveTansFromLanguage("英语")
                    PreferenceMgr.getInstance().translatePreference.saveTansToLanguage("中文（简体）")
                    val bitmap = getExampleBitmap()
                    processBitmap(bitmap,true)
                }
            }
        }
    }
}